<template>
  <div class="app-container">
    <Form
      :model="formState"
      autocomplete="off"
      :label-col="labelCol"
      :rules="rules"
      @finish="onSubmit"
    >
      <FormItem label="上级菜单">
        <Select
          v-model:value="formState.parentId"
          allow-clear
          placeholder="上级菜单"
          show-search
          :default-active-first-option="false"
          :filter-option="false"
          :not-found-content="null"
          :options="searchData"
          @search="handleSearch"
        />
      </FormItem>
      <FormItem label="忽略缓存" name="isIgnoreKeepAlive">
        <Switch v-model:checked="formState.isIgnoreKeepAlive" />
      </FormItem>
      <FormItem label="标题" name="title">
        <Input v-model:value="formState.title" allow-clear placeholder="标题" />
      </FormItem>
      <FormItem label="名称" name="name">
        <Input v-model:value="formState.name" allow-clear placeholder="如不填默认同标题" />
      </FormItem>
      <FormItem label="路径" name="path">
        <Input v-model:value="formState.path" allow-clear placeholder="路径" />
      </FormItem>
      <FormItem label="组件" name="component">
        <Input v-model:value="formState.component" allow-clear placeholder="组件" />
      </FormItem>
      <FormItem label="图标">
        <Input v-model:value="formState.icon" allow-clear placeholder="图标" />
      </FormItem>
      <FormItem label="排序">
        <InputNumber v-model:value="formState.menuOrder" />
      </FormItem>
      <FormItem>
        <a-button type="primary" html-type="submit" :loading="btnLoading">提交</a-button>
      </FormItem>
    </Form>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { Form, FormItem, Input, Switch, InputNumber, Select } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { addMenu, fuzzy } from '/@/api/sys/menu'

  const emit = defineEmits(['onSuccess'])

  const labelCol = { style: { width: '80px' } }

  const rules: Record<string, Rule[]> = {
    title: [{ required: true, trigger: 'change', message: '标题不能为空' }],
    path: [{ required: true, trigger: 'change', message: '名称不能为空' }],
    component: [{ required: true, trigger: 'change', message: '组件不能为空' }],
  }

  const formState = ref({
    title: '',
    name: '',
    path: '',
    component: '',
    icon: '',
    parentId: '',
    isIgnoreKeepAlive: false,
    menuOrder: 0,
  })

  const btnLoading = ref(false)

  const onSubmit = () => {
    btnLoading.value = true
    addMenu(formState.value).then(() => {
      btnLoading.value = false
      emit('onSuccess')
    })
    // console.log(formState.value)
  }

  const searchData: any = ref([])
  const handleSearch = (v) => {
    if (v) {
      fuzzy(v).then((data) => {
        const temp: any = []
        data.forEach((r) => {
          temp.push({ value: r.objectId, label: r.objectName })
        })
        searchData.value = temp
      })
    }
  }
</script>
